$(function () {
  //1.初始化Table
  var oTable = new TableInit();
  oTable.Init();
  //2.初始化Button的点击事件
  var oButtonInit = new ButtonInit();
  oButtonInit.Init();
});
var TableInit = function () {
  var oTableInit = new Object();
  //初始化Table
  oTableInit.Init = function () {
    $('#tb_departments').bootstrapTable({
      url: 'userlist',		 //请求后台的URL（*）
      method: 'get',      //请求方式（*）
      toolbar: '#toolbar',    //工具按钮用哪个容器
      striped: true,      //是否显示行间隔色
      cache: true,      //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
      pagination: true,     //是否显示分页（*）
      sortable: true,      //是否启用排序
      sortOrder: "asc",     //排序方式
      queryParams: oTableInit.queryParams,//传递参数（*）
      sidePagination: "server",   //分页方式：client客户端分页，server服务端分页（*）
      pageNumber:1,      //初始化加载第一页，默认第一页
      pageSize: 10,      //每页的记录行数（*）
      pageList: [10, 25, 50, 100],  //可供选择的每页的行数（*）
      search: false,      //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
      strictSearch: true,
      showColumns: false,     //是否显示所有的列
      showRefresh: false,     //是否显示刷新按钮
      minimumCountColumns: 2,    //最少允许的列数
      clickToSelect: true,    //是否启用点击选中行
      //height: 550,      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
      uniqueId: "pid",      //每一行的唯一标识，一般为主键列
      showToggle:false,     //是否显示详细视图和列表视图的切换按钮
      cardView: false,     //是否显示详细视图
      detailView: false,     //是否显示父子表
      responseHandler:responseHandler,
      columns: [{
        checkbox: true
      }, {
        	field: 'userName',
        	title: '用户名'
      }, {
      		field: 'host',
		  	title: 'Ip地址'
      }, {
        	field: 'realName',
        	title: '真实姓名'
      }, {
        	field: 'email',
        	title: '邮箱'
      }, {
        	field: 'phone',
        	title: '电话'
      }, {
        	field: 'status',
        	title: '是否启用',
        	formatter:function(value,row,index){
            	if(value==1){
            		return "已启用";
            	}else{
            		return "未启用";
            	}
        	}
      	}]
    	});
  	};
  //得到查询的参数
  oTableInit.queryParams = function (params) {
    var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
      limit: params.limit,   //页面大小
      offset: params.offset,  //页码
      departmentname1: $("#txt_search_departmentname1").val(),
      departmentname2: $("#txt_search_departmentname2").val(),
      order:params.order,
      statu: $("#txt_search_statu").val()
    };
    return temp;
  };
  return oTableInit;
};
var ButtonInit = function () {
  var oInit = new Object();
  var postdata = {};
  oInit.Init = function () {
    //初始化页面上面的按钮事件
  };
  return oInit;
};

$(function () {
	$("#btn_query").bind("click",function(){
		$('#tb_departments').bootstrapTable('refresh');
	});
});
function responseHandler(res) {
	return res;
}
function showlock(){
	window.parent.window.lock();
	return false;
}
function add(){
	var val = new validate({
		/*rules里面是检验规则，
		*key为需要检验的input的id,
		*value为此input对应的检验规则
		*/
		rules:{
			UserName:"endlish",
            Host:"notEmpty",
            PassWord:"notEmpty",
			RealName:"notEmpty",
			Mail:"email",
			Phone:"tel"
		},
		/*submitFun里面为检验成功后要执行的方法*/
		submitFun:function(){
			var user = new Object();
			user.userName=$("#UserName").val();
			user.password=$("#PassWord").val();
			user.realName=$("#RealName").val();
			user.host=$("#Host").val();
			user.email=$("#Mail").val();
			user.phone=$("#Phone").val();
			user.status=$("#Enable").val();
			var zTree =$.fn.zTree.getZTreeObj("tree");
			var nodes = zTree.getCheckedNodes();
			for(i=0;i<nodes.length;i++){
				user['roles['+i+'].pid']=nodes[i].pid;
			}
			var options = {
		            url: 'doSave',
		            type: 'post',
		            dataType: 'json',
		            data:user,
		            success: function (data) {
		                if(data.success){
		                	refreshTable();
		                	$("#modal").remodal().close();
		                }
		                swal(data.msg);
		            }
		        };
		 $.ajax(options);
		}
	})
}
function edit(pid){
	var val = new validate({
		/*rules里面是检验规则，
		*key为需要检验的input的id,
		*value为此input对应的检验规则
		*/
		rules:{
			UserName:"endlish",  
			PassWord:"notEmpty",
            Host:"notEmpty",
			RealName:"notEmpty",
			Mail:"email",
			Phone:"tel"
		},
		/*submitFun里面为检验成功后要执行的方法*/
		submitFun:function(){
		var user=new Object();
		user=$('#tb_departments').bootstrapTable('getRowByUniqueId',pid);
		delete user.roles;
		user.createTime=new Date(user.createTime);
		user.userName=$("#UserName").val();
		user.password=$("#PassWord").val();
		user.host=$("#Host").val();
		user.realName=$("#RealName").val();
		user.email=$("#Mail").val();
		user.phone=$("#Phone").val();
		user.status=$("#Enable").val();
		var zTree =$.fn.zTree.getZTreeObj("tree");
		var nodes = zTree.getCheckedNodes();
		for(i=0;i<nodes.length;i++){
			user['roles['+i+'].pid']=nodes[i].pid;
		}
		var options = {
	            url: 'doUpdate',
	            type: 'post',
	            dataType: 'json',
	            data:user,
	            success: function (data) {
	                if(data.success){
	                	refreshTable();
	                	$("#modal").remodal().close();
	                }
	                swal(data.msg);
	            }
	        };
	 $.ajax(options);
		}
	})
}
function addShow(){
	$("#modalTitle").text("新建用户");
	$("#UserName").val('');
	$("#UserName").removeAttr('readonly');
	$("#PassWord").val('');
    $("#Host").val('');
	$("#RealName").val('');
	$("#Mail").val('');
	$("#Phone").val('');
	$("#Enable").val('1');
	$("#Config").attr('onclick','add()');
	var zTree =$.fn.zTree.getZTreeObj("tree");
	zTree.checkAllNodes(false);
	$("#modal").remodal().open();
}
function editShow(){
	var selects = $("#tb_departments").bootstrapTable('getSelections');
	if(selects.length>0){
		if(selects.length==1){
			$("#modalTitle").text("修改用户");
			$("#UserName").val(selects[0].userName);
			$("#UserName").attr('readonly','readonly');
            $("#Host").val(selects[0].host);
			$("#PassWord").val('');
			$("#RealName").val(selects[0].realName);
			$("#Mail").val(selects[0].email);
			$("#Phone").val(selects[0].phone);
			$("#Enable").val(selects[0].status);
			$("#Config").attr('onclick','edit('+selects[0].pid+')');
			var zTree =$.fn.zTree.getZTreeObj("tree");
			zTree.checkAllNodes(false);
			var roles=selects[0].roles;
			for(i=0;i<roles.length;i++){
				var node = zTree.getNodeByParam("pid",roles[i].pid);
				zTree.checkNode(node, true, true);
			}
			$("#modal").remodal().open();
		}else{
			swal("修改只能选择1行数据");
		}
	}else{
		swal("至少选择1行数据");
	}
}
function deletebypid(){
	var selects = $("#tb_departments").bootstrapTable('getSelections');
	var pids=new Array();
	for (var i=0;i<selects.length;i++){
		pids[i]=selects[i].pid;
	}
	var options = {
            url: 'logicDelete',
            type: 'post',
            dataType: 'text',
            data:{'pids':JSON.stringify(pids)},
            success: function (data) {
                if (data.length > 0)
                	var obj = jQuery.parseJSON(data);
                if(obj.success){
                	refreshTable();
                	$("#modal").remodal().close();
                	swal("删除成功!", 
            				"你选择的用户已经删除.", 
            				"success"
            				); 
                }else{
                	swal(obj.msg);
                }
            }
        };
 $.ajax(options);
}
function deleteCon(){
	var selects = $("#tb_departments").bootstrapTable('getSelections');
	if(selects.length>0){
		swal({   title: "你确定要删除?",  
			text: "用户删除后将无法找回!",  
			type: "warning",   
			showCancelButton: true,   
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "确定!",
			cancelButtonText: "取消",
			closeOnConfirm: false },
			function(){   
				deletebypid();
			});
	}else{
		swal("至少选择1行数据");
	}
}
function refreshTable(){
	$("#tb_departments").bootstrapTable('refresh');
}
var setting = {
        check: {
            enable: true
        },
        view: {
            dblClickExpand: false,
            showLine: true,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable:true,
                idKey: "pid",
                rootPId: ""
            }
        },
        callback: {
            beforeClick: function(treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("tree");
                if (treeNode.isParent) {
                    zTree.expandNode(treeNode);
                    return false;
                } else {
                    demoIframe.attr("src",treeNode.file + ".html");
                    return true;
                }
            }
        }
    };
   function showtree(zNodes) {
    	var t = $("#tree");
        demoIframe = $("#testIframe");
        demoIframe.bind("load", loadReady);
        t = $.fn.zTree.init(t, setting, zNodes);
    }
    function loadReady() {
        var bodyH = demoIframe.contents().find("body").get(0).scrollHeight,
                htmlH = demoIframe.contents().find("html").get(0).scrollHeight,
                maxH = Math.max(bodyH, htmlH), minH = Math.min(bodyH, htmlH),
                h = demoIframe.height() >= maxH ? minH:maxH ;
        if (h < 530) h = 530;
        demoIframe.height(h);
    }
    var rolelist=null;

    $( function(){
    	var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
    		      limit: 100,   //页面大小
    		      offset: 0,  //页码
    		    };
        $.ajax({

        	 type: 'get',

        	 url: '../systemrole/rolelist' ,
        	 
        	 cache:true,
        	 
        	 data: temp ,

        	 success: function(data){
        		 showtree(data.rows);
        	 } ,

        	 dataType: 'json'

        	});
        });
    
    /* function selecttree(arrayobj){
	var zTree =$.fn.zTree.getZTreeObj("tree");
	var temp=new Array();
	temp=arrayobj.split(',');
	for(i=0;i<temp.length;i++){
		var node = zTree.getNodeByParam("pid",temp[i]);
		zTree.checkNode(node, true, true);
	}
	$("#modal2").remodal().open();
}

function editrole(){
	var zTree =$.fn.zTree.getZTreeObj("tree");
	var nodes = zTree.getCheckedNodes();
	var user={
		pid:1,
		roles:[]
	};
	for(var i=0;i<nodes.length;i++) {
		var role=new Object();
		role.pid=nodes[i].id;
		user.roles.push(role);
	}
	var options = {
            url: 'doUpdate',
            type: 'post',
            dataType: 'text',
            data:user,
            success: function (data) {
                if (data.length > 0)
                	var obj = jQuery.parseJSON(data);
                if(obj.success){
                	refreshTable();
                	$("#modal2").remodal().close();
                }
                swal(obj.msg);
            }
        };
	$.ajax(options);
}
function showeditrole(){
	var zTree =$.fn.zTree.getZTreeObj("tree");
	zTree.checkAllNodes(false);
	var selects = $("#tb_departments").bootstrapTable('getSelections');
	if(selects.length>0){
		if(selects.length==1){
			var roles=selects[0].roles;
			for(i=0;i<roles.length;i++){
				var node = zTree.getNodeByParam("pid",roles[i].pid);
				zTree.checkNode(node, true, true);
			}
			$("#Config2").attr('onclick','editrole('+selects[0].pid+')');
			$("#modal2").remodal().open();
		}else{
			swal("修改只能选择1行数据");
		}
	}else{
		swal("至少选择1行数据");
	}
}*/